package com.ansion.utils;

import android.text.TextUtils;
import android.util.Log;
import android.util.Pair;

import androidx.core.text.BidiFormatter;

import com.ansion.log.VLog;
import com.ansion.string.Emoji;
import com.ansion.string.StringUtils;

import io.michaelrocks.libphonenumber.android.Phonenumber;

/**
 * created by zhaoyuntao
 * on 29/12/2021
 * description:
 */
public class ContactUtil {
    /**
     * 公众号统一sessionid必须以80802开头
     */
    public static final String OA_PREFIX = "80802";
    public static final String BOTIM_TEAM_ACCOUNT = "8080297091311";
    public final static String MENTION_ALL_UID = "456465108108564654";
    public static final long BOTIM_TEAM_ID = 8080297091311L;
    public static final String BOTIM_TEAM_ACCOUNT_DEPRECIATED = "10000";
    public static final int SOMA_NEWS_ID = 10001;

    //本地写死的payby公众号ID
    public static final long OA_PAY_BY_ID = 8080202;
    public static final int BOTIM_TEAM_ID_DEPRECIATED = 10000;
    public static final int BOTIM_FILE_ASSISTANT_ID = 10009;
    public static final int INVALID_ID = -1;
    private static String myUid;
    private static boolean isWebLogin;
    private static String mLoginToken;
    private static String mSessionTag;
    public static final int CHAT_TYPE_P2P = 0;
    public static final int CHAT_TYPE_GROUP = 1;
    public static final int CHAT_TYPE_PUBLIC_ACCOUNT = 2;

    public static boolean contactsPermissionChecked = false;
    public static boolean contactsPermissionDialogPopped = false;

    public static void setWebLogin(boolean isWebLogin) {
        ContactUtil.isWebLogin = isWebLogin;
    }

    public static boolean isWebLogin() {
        return isWebLogin;
    }

    public static boolean isLoggedIn() {
        return !TextUtils.isEmpty(myUid);
    }

    @Deprecated
    public static void setMyUid(long uid) {
        setMyUid(String.valueOf(uid));
    }

    public static void setLoginToken(String loginToken) {
        mLoginToken = loginToken;
    }

    public static String getLoginToken() {
        return mLoginToken;
    }

    public static void setSessionTag(String sessionTag) {
        mSessionTag = sessionTag;
    }

    public static String getSessionTag() {
        return mSessionTag;
    }

    public static void setMyUid(String uid) {
        myUid = uid;
    }

    public static String getMyUid() {
        return myUid;
    }

    public static String getLoginId() {
        return getMyUid();
    }

    @Deprecated
    public static long getMyUidLong() {
        return ValueSafeTransfer.longValue(myUid);
    }

    public static boolean isSelf(String userUid) {
        return !TextUtils.isEmpty(userUid) && TextUtils.equals(getLoginId(), userUid);
    }

    @Deprecated
    public static boolean isMySelf(long uid) {
        return isMySelf(String.valueOf(uid));
    }

    public static boolean isMySelf(String uid) {
        return isSelf(uid);
    }

    @Deprecated
    public static boolean isUser(long uid) {
        String uidString = String.valueOf(uid);
        return uid > 0 && isUser(uidString);
    }

    public static boolean isUser(String uid) {
        return !TextUtils.isEmpty(uid) && uid.length() < 17 && !uid.startsWith(OA_PREFIX);
    }

    @Deprecated
    public static boolean isGroup(long uid) {
        String uidString = String.valueOf(uid);
        return uid > 0 && isGroup(uidString);
    }

    public static boolean isGroup(String uid) {
        return !TextUtils.isEmpty(uid) && uid.length() > 17;
    }

    public static boolean isOAAccount(long uid) {
        String uidString = String.valueOf(uid);
        return uid > 0 && isOAAccount(uidString);
    }

    public static boolean isOAAccount(String uid) {
        return !TextUtils.isEmpty(uid) && uid.startsWith(OA_PREFIX);
    }

    @Deprecated
    public static int getType(long uid) {
        return getType(String.valueOf(uid));
    }

    /**
     * Please use {@link ContactUtil#isGroup(String)}to get the contact type.
     *
     * @param uid
     * @return
     */
    @Deprecated
    public static int getType(String uid) {
        if (ContactUtil.isGroup(uid)) {
            return CHAT_TYPE_GROUP;
        } else if (ContactUtil.isUser(uid)) {
            return CHAT_TYPE_P2P;
        } else {
            return CHAT_TYPE_PUBLIC_ACCOUNT;
        }
    }

    public static void clear() {
        if (VLog.OPEN_LOG)
            VLog.i("TAG_E2E", "ContactUtil.clear:" + ContactUtil.myUid + "\n" + Log.getStackTraceString(new Throwable()));
        ContactUtil.myUid = null;
        ContactUtil.isWebLogin = false;
        ContactUtil.mLoginToken = null;
        ContactUtil.mSessionTag = null;
    }


    public static boolean isFileAssistant(String uid) {
        long userId = ValueSafeTransfer.longValue(uid);
        return isFileAssistant(userId);
    }

    public static boolean isFileAssistant(long userId) {
        return userId == ContactUtil.BOTIM_FILE_ASSISTANT_ID;
    }


    public static boolean isSomaNews(String uid) {
        return TextUtils.equals(uid, String.valueOf(ContactUtil.SOMA_NEWS_ID));
    }

    public static boolean isBotimTeam(String uid) {
        long userId = ValueSafeTransfer.longValue(uid);
        return userId == BOTIM_TEAM_ID || userId == SOMA_NEWS_ID || userId == BOTIM_TEAM_ID_DEPRECIATED;
    }

    public static boolean isServerId(String uid) {
        long userId = ValueSafeTransfer.longValue(uid);
        return isServerId(userId);
    }

    /**
     * 是否是本地账号，比如payby，soma news这些，头像是写死的
     ***/
    public static boolean isLocalServerId(String uid) {
        long userId = ValueSafeTransfer.longValue(uid);
        return isServerId(userId) && !ContactUtil.BOTIM_TEAM_ACCOUNT.equals(uid);
    }


    /***
     * 是否是新的botim官方公众号
     * @param uid
     * @return
     */
    public static boolean isNewBotimTeam(String uid) {
        return ContactUtil.BOTIM_TEAM_ACCOUNT.equals(uid);
    }

    public static boolean isServerId(long userId) {
        return userId == ContactUtil.BOTIM_TEAM_ID
                || userId == ContactUtil.SOMA_NEWS_ID
                || userId == ContactUtil.BOTIM_FILE_ASSISTANT_ID
                || userId == ContactUtil.BOTIM_TEAM_ID_DEPRECIATED;
    }

    public static boolean isNormalSession(String sessionId) {
        if (TextUtils.isEmpty(sessionId))
            return false;
        return StringUtils.isDigitsOnly(sessionId);
    }

    public static String getRegionCode(String uid) {
        final Phonenumber.PhoneNumber fmatPhone = PhoneNumberHelper2.getNumber(uid);
        if (null != fmatPhone) {
            return PhoneNumberHelper2.getRegionCode(fmatPhone);
        }
        return null;
    }

    public static int getCountryInt(int countrycodeInt, String uid, String countryCode) {

        if (countrycodeInt < 0) {
            try {
                countrycodeInt = Integer.parseInt(countryCode);
            } catch (Exception e) {
                VLog.e("TAG_LOG_ERROR", e);
            }
        }
        // 做一层保护，避免countryCode错误时业务不会出错,因为soma的uid是带国家吗的手机号码 //add by jay
        if (countrycodeInt <= 0) {
            Phonenumber.PhoneNumber number = PhoneNumberHelper2.getNumber(uid);
            if (number != null) {
                countrycodeInt = number.getCountryCode();
            }
        }
        // end.

        return countrycodeInt;
    }

    @Deprecated
    public static boolean isSystemId(long userId) {
        return userId >= 10000 && userId <= 10010;
    }

    public static boolean isSystemId(String userId) {
        long userIdLong = ValueSafeTransfer.longValue(userId);
        return userIdLong >= 10000 && userIdLong <= 10010;
    }

    public static String getFormatPhone(String uid) {
        return getFormatPhone(ValueSafeTransfer.longValue(uid));
    }

    public static String getFormatPhone(long uid) {
        try {
            String formatPhone = BidiFormatter.getInstance().unicodeWrap(PhoneNumberHelper2.getInternationalFormat(uid));
            ;
            if (formatPhone != null && !formatPhone.isEmpty()) {
                return formatPhone;
            }
        } catch (Exception e) {
        }

        return BidiFormatter.getInstance().unicodeWrap("+" + uid);
    }

    public static boolean isBabaTeam(long userId) {
        return userId == ContactUtil.BOTIM_TEAM_ID;
    }

    public static boolean isBabaTeam(String userId) {
        return TextUtils.equals(userId, String.valueOf(ContactUtil.BOTIM_TEAM_ID));
    }

    public static boolean isSomaNews(long userId) {
        return userId == ContactUtil.SOMA_NEWS_ID;
    }


    public static String getUidByPhoneNumber(String phoneNumber) {
        return TextUtils.isEmpty(phoneNumber) ? phoneNumber : phoneNumber.replaceAll("\\D", "");
    }

    public static boolean isMentionAll(String uid) {
        return MENTION_ALL_UID.equals(uid);
    }


    public static String getDisplayText(String uid, String firstName, String lastName) {
        String text = "";
        String firstNameTrim = firstName == null ? "" : firstName.trim();
        String lastNameTrim = lastName == null ? "" : lastName.trim();
        if (!TextUtils.isEmpty(firstNameTrim) && !TextUtils.isEmpty(lastNameTrim)) {
            Pair<Boolean, String> characterFirst = Emoji.takeFirstCharacterPair(firstNameTrim);
            Pair<Boolean, String> characterSecond = Emoji.takeFirstCharacterPair(lastNameTrim);
            if (characterFirst.first || characterSecond.first) {//只要有emoji就只显示firstName的首字母
                text = characterFirst.second;
            } else {
                text = characterFirst.second + characterSecond.second;
            }
        } else {
            if (!TextUtils.isEmpty(firstNameTrim)) {
                text = Emoji.takeFirstCharacter(firstNameTrim);
            } else if (!TextUtils.isEmpty(lastNameTrim)) {
                text = Emoji.takeFirstCharacter(lastNameTrim);
            } else if (uid.length() > 2) {//取最后两位手机号
                text = uid.substring(uid.length() - 2);
            } else {
                text = uid;
            }
        }
        return text.toUpperCase();
    }
}
